<template>
  <div class="outer">
    <div class="three-container" ref="threeContainer"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick, onBeforeUnmount } from 'vue';
import { renderer, scene, camera } from "../../indexZJ"; // 你已有的Three.js初始化模块

const threeContainer = ref<HTMLElement | null>(null);
let resizeObserver: ResizeObserver | null = null;

/**
 * 等待布局稳定（防止弹窗刚打开时尺寸为 0）
 */
const waitForStableLayout = async (el: HTMLElement) => {
  return new Promise<void>(resolve => {
    const check = () => {
      const width = el.offsetWidth;
      const height = el.offsetHeight;
      if (width > 0 && height > 0) {
        resolve();
      } else {
        requestAnimationFrame(check);
      }
    };
    check();
  });
};

onMounted(async () => {
  await nextTick();

  const container = threeContainer.value;
  if (!container) return;

  await waitForStableLayout(container); // 等待弹窗渲染完毕再初始化

  const updateSize = () => {
    const width = container.offsetWidth;
    const height = container.offsetHeight;
    renderer.setSize(width, height);
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
  };

  container.appendChild(renderer.domElement);
  updateSize(); // 初始更新尺寸

  // 启动动画循环
  const animate = () => {
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
  };
  animate();

  // 监听尺寸变化
  resizeObserver = new ResizeObserver(() => {
    updateSize();
  });
  resizeObserver.observe(container);
});

onBeforeUnmount(() => {
  resizeObserver?.disconnect();
});
</script>

<style scoped>
.outer {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.three-container {
  width: 100%;
  height: 100%;
  background-color: black;
  position: relative;
  overflow: hidden;
}
</style>
